package com.zhou.util;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

/**
 * @author lang.zhou
 * @date 2020/1/2
 */
public class CharsetUtil {
    /*public static void main(String[] args) throws Exception {

        String s1 = changeCharset("这里","ISO-8859-1");
    }*/
    public static boolean isAllowCharset(String charset){
        try{
            Charset.forName(charset);
            return true;
        }catch (Exception e){
            return false;
        }
    }
    public static String changeCharset(String str, String newCharset)
            throws UnsupportedEncodingException {
        //用默认字符编码解码字符串。
        byte[] bs = str.getBytes();
        return new String(bs, newCharset);
    }
    /**
     * 判断是否为ISO-8859-1
     */
    public static boolean canEncode(String str,String charset) {
        return Charset.forName(charset).newEncoder().canEncode(str);
    }
    public static byte[] toBytes(String a,String charset){
        try {
            return a.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
    public static String toString(byte[] b,String charset){
        try {
            return new String(b,charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}
